<?php

namespace App\Services;

use App\Models\Area;
use App\Models\City;
use App\Models\Province;
use App\Models\School;
use App\Models\SchoolRule;
use Illuminate\Http\Request;

/**
 * Class SchoolService
 * @package App\Services
 * 学校
 */
class SchoolService
{
    /**
     * @param Request $request
     * @return mixed
     * 新增学校 && 添加默认规则
     */
    public static function add(Request $request)
    {
        $school = School::create(array_merge($request->all(), [
            'province' => $request->areaId[0],
            'city' => $request->areaId[1],
            'country' => $request->areaId[2],
            'address' => Province::where('provinceid', $request->areaId[0])->first(['province'])->province
                . City::where('cityid', $request->areaId[1])->first(['city'])->city
                . Area::where('areaid', $request->areaId[2])->first(['area'])->area
        ]));
        // 添加默认的学校规则
        SchoolRule::create([
            'school_id' => $school->id
        ]);
        return $school;
    }

    /**
     * @param School $school
     * @return School
     * 编辑学校
     */
    public static function edit(School $school)
    {
        $request = \request();
        $school->fill($request->all());
        $school->province = $request->areaId[0];
        $school->city = $request->areaId[1];
        $school->country = $request->areaId[2];
        $school->address = Province::where('provinceid', $school->province)->first(['province'])->province
            . City::where('cityid', $school->city)->first(['city'])->city
            . Area::where('areaid', $school->country)->first(['area'])->area;
        $school->save();
        return $school;
    }
}
